interface CurlData {
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD';
  url: string;
  queryParams: Record<string, string>;
  headers: Record<string, string>;
  body: Record<string, any> | string | null;
}

function extractCurlData(curlCommand: string): CurlData {
  const result: CurlData = {
    method: 'GET',
    url: '',
    queryParams: {},
    headers: {},
    body: null,
  };

  // 1. 提取 HTTP 方法（支持 --request/-X）
  const methodMatch = curlCommand.match(/(?:--request|-X)\s+(GET|POST|PUT|DELETE|PATCH|HEAD)/i);
  if (methodMatch) {
    result.method = methodMatch[1].toUpperCase() as CurlData['method'];
  }

  // 2. 提取 URL（支持单/双引号）
  const urlMatch = curlCommand.match(/(?:'|")(https?:\/\/[^'"]+)(?:'|")/);
  if (urlMatch) {
    result.url = urlMatch[1];
    
    // 提取所有请求的查询参数
    const queryString = result.url.split('?')[1];
    if (queryString) {
      queryString.split('&').forEach(pair => {
        const [key, value] = pair.split('=');
        result.queryParams[decodeURIComponent(key)] = decodeURIComponent(value || '');
      });
    }
  }

  // 3. 提取请求头（支持 -H/--header）
  const headerRegex = /(?:-H|--header)\s+(?:'|")([^'"]+)(?:'|")/g;
  let headerMatch;
  while ((headerMatch = headerRegex.exec(curlCommand)) !== null) {
    const [_, header] = headerMatch;
    const [key, value] = header.split(/\s*:\s*/);
    result.headers[key] = value;
  }

  // 4. 提取请求体（支持 --data-raw/--data/-d）
  const bodyRegex = /(?:--data-raw|--data|-d)\s+(['"])([\s\S]*?)\1/g;
  const bodyMatch = bodyRegex.exec(curlCommand);
  if (bodyMatch) {
    const rawBody = bodyMatch[2].trim();
    try {
      // 尝试解析 JSON（包括多行格式）
      result.body = JSON.parse(rawBody.replace(/\n/g, ''));
    } catch {
      if (rawBody.includes('=')) {
        // 处理 URL-encoded 格式
        result.body = {};
        rawBody.split('&').forEach(pair => {
          const [key, value] = pair.split('=');
          (result.body as Record<string, string>)[decodeURIComponent(key)] = decodeURIComponent(value || '');
        });
      } else {
        // 保留原始格式
        result.body = rawBody;
      }
    }
  }

  return result;
}

export default extractCurlData
